"use strict";
const pkgDir = require("pkg-dir").sync;
const path = require("path");
const formatPath = require("@hcnhistudy/format-path");
const npminstall = require("npminstall");
const pathExists = require("path-exists").sync;
const fse = require("fs-extra"); // 比原生的 fs 模块更好用
const {
  getDefineRegistry,
  getNpmLatestVersion,
} = require("@hcnhistudy/get-npm-info");
class Package {
  constructor(options) {
    if (!options) return;
    if (Object.prototype.toString.call(options) !== "[object Object]") return;
    this.targetPath = options.targetPath;
    this.storeDir = options.storeDir; // C:\Users\Administrator\.hcnhistudy-cli\dependencies\node_modules
    this.packageName = options.packageName;
    this.packageVersion = options.packageVersion;
    // 生成package的缓存目录前缀
    this.cacheFilePathPrefix = this.packageName.replace("/", "_");
  }
  /// 把 latest 版本号，获取最新版本
  async prepare() {
    if (this.packageVersion === "latest") {
      const packageVersion = await getNpmLatestVersion(this.packageName);
      if (packageVersion) this.packageVersion = packageVersion;
    }
    // 缓存目录不存在，创建缓存目录
    if (this.storeDir && !pathExists(this.storeDir)) {
      fse.mkdirpSync(this.storeDir); //创建缓存目录
    }
  }

  get cacheFilePath() {
    return path.resolve(
      this.storeDir,
      `_${this.cacheFilePathPrefix}@${this.packageVersion}@${this.packageName}`
    );
  }
  // 生成指定版本路径
  getSpecificCacheFilePath(packageVersion) {
    return path.resolve(
      this.storeDir,
      `_${this.cacheFilePathPrefix}@${packageVersion}@${this.packageName}`
    );
  }
  // 检查当前package是否存在
  async exists() {
    console.log(this.storeDir);
    if (this.storeDir) {
      await this.prepare();
      //   console.log(this.cacheFilePath)
      return pathExists(this.cacheFilePath);
    } else {
      return pathExists(this.targetPath);
    }
  }
  // 安装包
  async install() {
    await this.prepare();
    await npminstall({
      root: this.targetPath, // 模块路径
      storeDir: this.storeDir, // 缓存 package 的存储路径
      registry: getDefineRegistry(), // 源
      pkgs: [
        {
          name: this.packageName,
          version: this.packageVersion,
        },
      ],
    });
  }
  // 更新包
  async update() {
    await this.prepare();
    // 1.获取最新的版本号
    const latestPackageVersion = await getNpmLatestVersion(this.packageName);
    if (!latestPackageVersion) {
      return;
    }
    // 2.查询最新版本号对于的路径是否存在
    const latestFilePath = this.getSpecificCacheFilePath(latestPackageVersion);
    // 3.如果不存在，则直接安装最新版本
    if (!pathExists(latestFilePath)) {
      //   console.log(latestFilePath);
      try {
        await npminstall({
          root: this.targetPath, // 模块路径
          storeDir: this.storeDir, // 缓存 package 的存储路径
          registry: getDefineRegistry(), // 源
          pkgs: [
            {
              name: this.packageName,
              version: latestPackageVersion,
            },
          ],
        });
        // 更新 packageVersion
        this.packageVersion = latestPackageVersion;
      } catch (e) {
        console.log(e, "pppppppppppp");
      }
    }
    return latestFilePath;
  }

  // 获取入口文件
  // es6 class get set 可以设置私有属性
  getRootFilePath() {
    //  pkg-dir 找到文件所在目录的读取package.json
    if (!this.targetPath) {
      console.error("targetPath 不存在");
      return;
    }
    // 获取一个要执行包路径的，执行入口文件
    function _getRootFile(targetPath) {
      const dir = pkgDir(targetPath);
      if (dir) {
        const pagFile = require(path.resolve(dir, "package.json"));
        if (pagFile && pagFile.main) {
          return formatPath(path.resolve(dir, pagFile.main));
        }
      }
    }
    // 缓存路径存在
    if (this.storeDir) {
      return _getRootFile(this.cacheFilePath);
    } else {
      // 不存在
      return _getRootFile(this.targetPath);
    }
  }
}

module.exports = Package;
